<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use phpDocumentor\Reflection\Types\Nullable;

class ProductRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @param Request $request
     * @return array
     */
    public function rules(Request $request)
    {
        return [
            //栏目
            'category_id'   => ['required',Rule::exists('categories','id')->where(function ($query){
                $query->whereNull('deleted_at');
            })],
            'keyword'   =>  'sometimes|string|min:2|max:32',
            'description'   =>  'sometimes|string|min:2|max:255',
            //新增的时候商品名唯一。
            //编辑的时候可能不修改名字。
            'title'         => ['required','string','max:512','min:2',
                                Rule::unique('products')->where(function ($query) use ($request) {
                                    if ($request->post('id')) {//编辑时，不能把名字修改为和已存在的其他商品名相同
                                        //return $query->where('cate_id',$request->post('cate_id'))->where('id','<>',$request->post('id'));
                                        return $query->where('id','<>',$request->post('id'));

                                    }else {//新增时
                                        //return $query->where('cate_id',$request->post('cate_id'));
                                    }
                                })
            ],
            'unit'          =>  'sometimes|string',
            'skus'           =>  'required|array',
            //todo  同一个商品的规格型号不能有重复
            'skus.*.title'   =>  'required|string|max:512|min:2',
            'skus.*.origin_price'   =>  'required|numeric|gt:0',
            'skus.*.sold_price'   =>  'required|numeric|lte:skus.*.origin_price',
            'skus.*.stock'  =>  'required|numeric|gt:0',
            'is_banner'   =>  'sometimes|integer',
            'cover'         =>  ['required'],
            'images'        =>  ['required','array'],
            'detail'        =>  ['required','string'],
            'sort'          =>  'integer|gte:0',
            'score'          =>  'integer|gte:0',
            'type'          =>  ['required', Rule::in(1, 2, 3)]
        ];
    }

}
